import 'package:flutter/material.dart';
import 'package:flutter_qr_reader/flutter_qr_reader.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:spendbook/common/constants.dart';
import 'package:spendbook/models/family.dart';
import 'package:spendbook/models/user.dart';

class ScanScreen extends StatefulWidget {
  ScanScreen({Key? key}) : super(key: key);

  @override
  _ScanScreenState createState() => new _ScanScreenState();
}

class _ScanScreenState extends State<ScanScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        alignment: Alignment.center,
        color: Colors.black,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            SizedBox(
              width: MediaQuery.of(context).size.width - 20,
              height: MediaQuery.of(context).size.width - 20,
              child: QrReaderView(
                width: MediaQuery.of(context).size.width - 20,
                height: MediaQuery.of(context).size.width - 20,
                callback: (QrReaderViewController controller) async {
                  final isGranted = await Permission.camera.request().isGranted;
                  if (isGranted) {
                    controller.startCamera((data, _) async {
                      final id = decodeQrCode(data);
                      Family family = Family()..family = (User()..id = int.parse(id));
                      await family.store();
                      Navigator.of(context).pushReplacementNamed('/family');
                    });
                  }
                },
              ),
            ),
            SizedBox(
              height: 100,
            ),
            Text(
              '请扫描家庭成员的名片',
              style: TextStyle(color: Colors.white, fontSize: 20.0),
            )
          ],
        ),
      ),
      appBar: AppBar(
        centerTitle: true,
        title: Text('扫码'),
      ),
    );
  }
}
